CBank = window.CBank || {};
CBank.fn = CBank.prototype = {
	/**
	 * 初始化
	 */
	init : function() {
		return this;
	}

};

CBank.porxyUrl = "/persion/api";
CBank.getParam = function(name, url) {
	if (!url)
		url = location.search; // 获取url中"?"符后的字串
	var params = {};
	var param = null;
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		var paramsArr = str.split("&");
		for ( var i = 0; i < paramsArr.length; i++) {
			var paramArr = paramsArr[i].split("=");
			var key = paramArr[0];
			paramArr.shift();
			var valus = paramArr.join("=");
			params[key] = valus;
		}
	}
	if (params[name]) {
		param = decodeURIComponent(params[name]);
	}
	return param;
};
CBank.requestJSONP = function(url, success, fail, o) {
	o = o || {
		notHideLoader : false,
		isbefore : false
	};
	var shop = window._shop || parent.window._shop;
	if (url.indexOf('_noLoader_') == -1) {
		if (shop) {
			shop.showLoad();
		}
	}
	// 服务器生产环境调试
	$.ajax({
		url : url,
		dataType : 'jsonp',
		success : function(result) {
			if (o.isbefore) {
				if (!o.notHideLoader) {
					var shop = window._shop || parent.window._shop;
					if (shop) {
						shop.hideLoad();
					}
				}
			}
			if (success) {
				success(result);
			}
			if (!o.isbefore) {
				if (!o.notHideLoader) {
					var shop = window._shop || parent.window._shop;
					if (shop) {
						shop.hideLoad();
					}
				}
			}
		},
		error : function(result) {
			if (o.isbefore) {
				if (!o.notHideLoader) {
					var shop = window._shop || parent.window._shop;
					if (shop) {
						shop.hideLoad();
					}
				}
			}
			if (fail) {
				fail(result);
			}
			if (!o.isbefore) {
				if (!o.notHideLoader) {
					var shop = window._shop || parent.window._shop;
					if (shop) {
						shop.hideLoad();
					}
				}
			}
		}
	});

};


CBank.loadSignArray = function(p) {
	var signArray = [];
	if (typeof p == 'object') {
		for ( var n in p) {
			if(p[n] == null || typeof p[n] == 'undefined'){
				p[n]="";
				signArray.push("");
			}else
			if (typeof p[n] == 'object') {
				signArray = signArray.concat(CBank.loadSignArray(p[n]));
			} else {
				signArray.push(p[n]);
			}
			;
		}
		;
	}
	return signArray;
};

CBank.loadSignStr = function(p) {
	var signArray = CBank.loadSignArray(p);
	//暂时不需要排序
	//signArray.sort();
	console.dir(signArray);
	//增加时间戳
	return signArray.join('');
};

CBank.config = {
		
	//UAT测试服务
//	webApp : 'http://211.147.64.62:85/',
//	checkcodeServerAddr : 'http://211.147.64.62:9090/',
//	commonServerAddr : 'http://211.147.64.62:9090/appapi/',
	
	
	
	//测试环境内网
	webApp : '@localAddr@',
	commonServerAddr : 'http://@serviceAddr@/appapi/',
	checkcodeServerAddr : 'http://@serviceAddr@/',
	alipaysubmitFrom:'@alipaysubmitFrom@',
	//测试环境内网
//	webApp : 'http://10.69.32.147:9090/',
//	commonServerAddr : 'http://192.168.20.230:8080/pegasusws/appapi/',
//	checkcodeServerAddr : 'http://192.168.20.180:8080/',
//	commonServerAddr : 'http://10.69.32.194/appapi/',
	
	//wb
//	commonServerAddr : 'http://192.168.20.230:8080/pegasusws/appapi/',
	//wr
//	commonServerAddr : 'http://10.69.32.133:8080/pegasusws/appapi/',
//	commonServerAddr : 'http://192.168.20.201:8080/pegasusws/appapi/',
//	cc
//	commonServerAddr : 'http://192.168.20.202:8080/pegasusws/appapi/',
	//wyd
//	commonServerAddr : 'http://192.168.20.237:8080/pegasusws/appapi/',
		
//	commonServerAddr : 'http://172.27.35.1:8080/pegasusws/appapi/',
	
//	commonServerAddr : 'http://10.69.32.33:8080/pegasusws/appapi/',
//	commonServerAddr : 'http://10.69.32.58:8080/pegasusws/appapi/',
	//dl
//	commonServerAddr : 'http://10.69.32.135:9090/pegasusws/appapi/',
	//lj
//	commonServerAddr : 'http://192.168.20.118:8080/pegasusws/appapi/',
	//zb
//	checkcodeServerAddr : 'http://10.69.32.229:8090/pegasusws/',
//	commonServerAddr : 'http://192.168.20.180:8080/pegasusws/appapi/',
//	commonServerAddr : 'http://10.69.32.229:8080/pegasusws/appapi/',
	//silo
//	commonServerAddr : 'http://10.69.32.134:8080/pegasusws/appapi/',
//	commonServerAddr : '/mei/appapi/',
	defaultImgAddr : '@localAddr@resources/images/error/',
	defaultImgAddr2 : '@localAddr@resources/images/error/',
	defaultImgAddr3 : '@localAddr@resources/images/error/',
	loginAddr:"menu/login.htm",
	appKey : '1903943638',
	secretkey : 'glsapp2014',
//	secretkey : '22d7ca6d21f64236b16826417350fde3'
};

CBank.loadGlobalParams = function(mdata) {
	mdata.platform_code = 'H5';
//	mdata.utmz = CBank.getSession("__utmz");
//	mdata.appKey = CBank.config.appKey, mdata.sign = '';
//	mdata.version = '1.0.1';
//	mdata.replyOriginal = '';
//	mdata.terminalType = 'html5';
};

CBank.loadMemberGlobalParams = function(mdata) {
//	mdata.terminalCode = 'html5', mdata.channelCode = 'CB_P';
//	mdata.businessPara = 'P';
};

CBank.ajaxBefore = function(o, apitype) {
//	if (apitype == 'member') {
//		var mtoken = CBank.getSession("per_token");
//		var mto = o.data.queryDto || o.data.dataDto || false;
//		if (mtoken && mto) {
//			mto.token = mtoken;
//			var mMemberCode = CBank.getSession("per_memberCode");
//			var mloginID = CBank.getSession("per_loginID");
//			if ("memberserv.jhtml?method=modifyMemberInfo" != o.url) {
//				if (!mto.memberCode) {
//					mto.memberCode = mMemberCode;
//				}
//				if (!mto.loginID) {
//					mto.loginID = mloginID;
//				}
//			}
//		}
//	}
};

CBank.ajaxSuccess = function(o,res, apitype) {
	if (o.url.indexOf('customer/login') != -1 || o.url.indexOf('customer/register') != -1) {
		CBank.setSession("mlh_mei_userId", res.user.userId);
		CBank.setSession("mlh_mei_userName", res.user.userName);
		CBank.setSession("mlh_mei_userEmail", res.user.userEmail);
		CBank.setSession("mlh_mei_credential", res.user.userCredentials);
	} else if (o.url.indexOf('customer/logout') != -1) {
		CBank.setSession("mlh_mei_credential", false);
	}	
};

CBank.fillAjaxBack = function(mdata){
	for(var n in mdata){
		if(typeof mdata[n] == 'string'){
			var mtag = $('[bc_id="'+n+'"]');
			if(mtag&&mtag[0]){
				var prefix = mtag.attr('_pre')||'';
				var suffix = mtag.attr('_suf')||'';
				if(mtag[0].tagName == 'INPUT'||mtag[0].tagName == 'TEXTAREA'){
					mtag.val(prefix+mdata[n]+suffix);
				}else{
					mtag.html(prefix+mdata[n]+suffix);
				}
			}
		}else if(typeof mdata[n] == 'object'){
			if(mdata[n].length||mdata[n].length==0){
				var mtag = $('[bc_list="'+n+'"]');
				var temp = mtag.find('[bc_list_item]')[0]?mtag.find('[bc_list_item]')[0].outerHTML:false;
				mtag.empty();
				if(temp){
					$(mdata[n]).each(function(){
						var m_data = this;
						var mval = temp;
						for(var n_n in m_data){
							mval  = mval.replace('${'+n_n+'}',m_data[n_n]);
						}
						$(mval).appendTo(mtag);
					});
				}
			}else{
				CBank.fillAjaxBack(mdata[n]);
			}
		}
	}
};

CBank.ajaxBackFn = function(o, mconfig, res) {
	try {
		var moutput = mconfig.output;
		for ( var n in moutput) {
			var mparam = moutput[n];
			if (mparam.type != 'array' && mparam.type != 'object') {
				if (typeof mparam.backfn == 'function') {
					backfn(res);
				} else {
					$('[id^="' + mparam.name + '_"]').each(function() {
						var idstr = this.id.split('_');
						if (idstr.length == 2) {
							var mfn = idstr[1];
							if (mfn == 'v') {
								$(this).val(res[mparam.name]);
							} else if (mfn == 'h') {
								$(this).html(res[mparam.name]);
							} else if (typeof o[mfn] == 'function') {
								o[mfn](def);
							}
						}
					});
				}
			}
		}
	} catch (e) {
		CBank.toast(e);
	}
};

CBank.ajax = function(o, apitype, def, fns) {
	apitype = apitype || 'common';
	CBank.ajaxBefore(o, apitype);
//	var fnname = o.url.replace(/\.api/g, '').replace(/\//g, '_').replace('.jhtml?method=', '_');

	o.url = CBank.config[apitype + 'ServerAddr'] + o.url;
	var signStr = '';

	if ('common' == apitype || "checkcode" == apitype) {
		signStr = CBank.loadSignStr(o.data);
		CBank.loadGlobalParams(o.data);
		signStr = CBank.config.secretkey + signStr;
		//get请求需要做缓存 不做加密
		if(!(o.type && o.type=="get")){
			var timestamp = new Date().getTime();
			o.data.timestamp = timestamp;
			signStr+=timestamp;
		}
		o.data.summary = $.md5(signStr);
		
	}
	console.info(signStr);

	if (def || CBank.isMock) {
		if (!def) {
			if (CBank.apidefault && CBank.apidefault[apitype] && CBank.apidefault[apitype][fnname]) {
				def = CBank.apidefault[apitype][fnname];
			} else {
				console.info('MOCK模式下,未设置默认返回值!');
			}
		}

		if (CBank.apiconfig && CBank.apiconfig[apitype] && CBank.apiconfig[apitype][fnname]) {
			CBank.ajaxBackFn(o, CBank.apiconfig[apitype][fnname], def);
		}

		if (typeof o.success == 'function') {
			window.setTimeout(function() {
				o.success(def);
			}, 2000);
		} else {
			CBank.toast('MOCK模式下,未定义成功回调函数!');
		}
		return;
	}

	if (CBank.showAjaxLoading) {
		CBank.getAjaxLoading().show();
	}
	var async;
	if (o.async == "false" || o.async == false) {
		async = false;
	} else {
		async = true;
	}
	$.ajax({
		type : o.type || "post",
		dataType : o.dataType || "json",
		url : o.url,
		async:async,
		timeout:o.timeout||30000,
		data : o.data,
		crossDomain : true,
		success : function(res) {
			if (CBank.showAjaxLoading) {
				CBank.getAjaxLoading().hide();
			}
			if (res) {
				if('common' == apitype && res.errorNum =='0'){
					CBank.ajaxSuccess(o,res);
				}
				if (typeof o.success == 'function') {
					o.success(res);
				}
			} else {
				CBank.toast("返回结果为空");
			}
		},
		error : function(res) {
			if (CBank.showAjaxLoading) {
				CBank.getAjaxLoading().hide();
			}
			if (typeof o.error == 'function') {
				o.error(res);
			}
		}
	});
};

// 默认跳登录
CBank.isLogin = function(url) {
	var token = CBank.getSession("mlh_mei_credential");
	if (token) {
		return true;
	} else {
		CBank.gotoUrl("menu/login",CBank.config.webApp+"menu/login.htm");
	}
};
// 默认跳登录
CBank.toLogin = function() {
	CBank.getSession("mlh_mei_credential","false");
	CBank.gotoUrl("menu/login",CBank.config.webApp+"menu/login.htm");
};
//登出
CBank.loginOut = function(url) {
	CBank.ajax({
		url:"customer/logout",
		type:"post",
		async:false,
		data:{
			"credential":CBank.getSession("mlh_mei_credential")
		},
		error:function(){
			CBank.toast("服务器忙！");
		},
		success:function(res){
			if(res.errorNum == "0"){
				CBank.setSession("mlh_mei_credential","");
//				window.location.reload();
				url = url?url:CBank.config.webApp+'index.html';
				window.location.href = url;
			}else{
				CBank.toast(res.errorMsg);
			}
		}
	});
	
};
//通过微信进来带openId的自动登陆
CBank.winLoginOut = function(openId) {
	CBank.ajax({
		 url:"customer/wechatLogin",
		 type:"post",
		 async:false,
		 data:{
			 "openId":openId
		 },
		 error:function(){
			 CBank.toast("服务器忙！");
		 },
		 success:function(res){
			if(res.errorNum == "0"){
				CBank.setSession("mlh_mei_userId", res.user.userId);
 				CBank.setSession("mlh_mei_userName", res.user.userName);
 				CBank.setSession("mlh_mei_userEmail", res.user.userEmail);
 				CBank.setSession("mlh_mei_credential", res.user.userCredentials);
			}else{
				
			}
		}
	});
	
};
/**
 * 通过ajax异步获取用户输入账号是否存在
 * tiananyang 
 * 2014-11-27
 */
function AccountIsHad(account){
	var str_result = null;
	$.ajax({
		type:"post",
		datatype:"json",
		async:false,
		url:'/user/accountIsHad',
		success:function(msg){
			str_result =msg.result;
			return str_result;
		},
		error:function(){
			str_reuslt="fail";
		},
	});
	return str_result;
}
//判断是否为微信登陆
CBank.isWeixin = function(){  
    var ua = navigator.userAgent.toLowerCase();  
    if(ua.match(/MicroMessenger/i)=="micromessenger") {  
        return true;  
    } else {  
        return false;  
    }  
}  
//登录路由，需要登录过滤的url
var routeUrl = [ 'menu/',"other/"];
var mhref = ["getpwd_step","mymeilihui_bandEmail_success","mymeilihui_modifyBandEmail_success"];
CBank.cartViewCount = function(callback){
	if(!CBank.getSession("mlh_mei_credential")){
		callback(0);
		return ;
	}
	CBank.ajax({
		url:"cart/viewCount",
		type:"get",
//		 async:false,
		data:{
			"credential":CBank.getSession("mlh_mei_credential")
		},
		error:function(){
		},
		success:function(res){
			if(res.errorNum == "0"){
				CBank.setSession("cartViewCount",res.itemCount);
				if (typeof callback == 'function') {
					callback(res.itemCount);
				}
			}else{
				isAjax1=false;
				CBank.toast(res.errorInfo);
			}
		}
	});
};
//获取用户信息
CBank.getMemberInfo = function(async){
	if(!CBank.getSession("mlh_mei_credential")){
		return ;
	}
	CBank.loading(true);
     //分类
    CBank.ajax({
//		url:"myaccount/info",
		 url:"myaccount/info4H5",
		 type:"get",
		 async:async==false?false:true,
		 data:{
			 "credential":CBank.getSession("mlh_mei_credential")
		 },
		 error:function(){
			 CBank.loading(false);
		 },
		 success:function(res){
			 CBank.loading(false);
			if(res.errorNum == "0"){
				CBank.setSession("mlh_memberInfo", memberInfo);
			}else{
				CBank.toast(res.errorInfo);
			}
		}
	 });
};

/**
 * modalName 跳转页面的模块名（唯一表示如 menu/login）
 * url	   跳转的页面
 * backUrl 需要指定返回的页面
 */
CBank.gotoUrl = function(modalName, url,forwardUrl,backUrl) {
	var needlogin = true;
	if(!url || !modalName){
		return false;
	}
	backUrl = backUrl || window.location.href;
	if (modalName){
//		for (var i = 0; i < routeUrl.length; i++) {
//			var thehref = routeUrl[i];
//			if (modalName == thehref) {
//				needlogin = true;
//				break;
//			}
//		}
		if(modalName.indexOf("other/") != -1||modalName.indexOf("menu/") != -1||modalName.indexOf("index") != -1||modalName.indexOf("silo") != -1 ||modalName.indexOf("user") != -1){
			needlogin = false;
		}else{
			for ( var i = 0; i < mhref.length; i++) {
				var thehref = mhref[i];
				if (modalName.indexOf(thehref) != -1) {
					needlogin = false;
					break;
				}
			}
		}
		//如果配置isgoHome 代表未登录返回
		CBank.setSession("mlh_mei_route_" + modalName + "_back", backUrl?backUrl:window.location.href);
		CBank.setSession("mlh_mei_route_" + modalName + "_forward", forwardUrl?forwardUrl:false);
	}else{
		needlogin = false;
	}
	var href = url;
	if (needlogin) {
		var credential = CBank.getSession("mlh_mei_credential");
		if (!credential){
			CBank.gotoUrl("menu/login",CBank.config.webApp+CBank.config.loginAddr,url);
			return false;
		}
	}
	window.location.href = href;
	return true;
};
//跳转上次跳转的URL
CBank.getBackUrl = function(modalName,url) {
	if (modalName && CBank.getSession("mlh_mei_route_" + modalName + "_back")) {
		url = CBank.getSession("mlh_mei_route_" + modalName + "_back");
		CBank.deleteSession("mlh_mei_route_" + modalName + "_back");
		CBank.deleteSession("mlh_mei_route_" + modalName + "_forward");
	}
	url = url? url:CBank.config.webApp+"index.html";
	window.location.href = url;
	return true;
};
//跳转到指向的URL
CBank.getForwardUrl = function(modalName,url) {
	if (modalName && CBank.getSession("mlh_mei_route_" + modalName + "_forward")) {
		url = CBank.getSession("mlh_mei_route_" + modalName + "_forward");
	}else
	if (modalName && CBank.getSession("mlh_mei_route_" + modalName + "_back")) {
		url = CBank.getSession("mlh_mei_route_" + modalName + "_back");
	}
	CBank.deleteSession("mlh_mei_route_" + modalName + "_back");
	CBank.deleteSession("mlh_mei_route_" + modalName + "_forward");
	url = url? url:CBank.config.webApp+"index.html";
	window.location.href = url;
	return true;
};



CBank.getSession = function(name) {
	var key = $.cookie(name);
	if (key && key.indexOf("{") != -1) {
		key = $.evalJSON(key);
	}
	if (key == "false") {
		key = null;
	}
	return key;
};

CBank.setSession = function(name, value, option) {
	if (typeof value != "string") {
		value = $.toJSON(value);
	}
	option = option || {
		path : "/",
		expires : 30
	};
	return $.cookie(name, value, option);
};
CBank.deleteSession = function(name) {
	$.cookie(name, null, {
		expires : -1,
		path : '/'
	});
};
CBank.valid = function(mconfig, o) {
	if (o && o.data) {
		for ( var n in o.data) {
			if (mconfig && mconfig.input && mconfig.input[n]) {
				var mparam = mconfig.input[n];
				if (!mparam.empty && !(o.data[n] && o.data[n] != '')) {
					CBank.toast(mparam.des + '不可为空!');
					return false;
				}
			}
		}
	}
	return true;
};
/**
 * 判断密码强度
 * 
 *	测试某个字符是属于哪一类.
 *	2014-11-28 
 */
function CharMode(iN){ 
	if (iN>=48 && iN <=57) //数字 
	return 1; 
	if (iN>=65 && iN <=90) //大写字母 
	return 2; 
	if (iN>=97 && iN <=122) //小写 
	return 4; 
	else 
	return 8; //特殊字符 
} 
/**
 * 返回密码的强度级别
 */
CBank.checkStrong = function(sPW){ 
	var Modes=0;
	//字符类型
	var liter = 0;
	//数字类型
	var num = 0;
	//特殊字符
	var spical = 0;
	//大写
	var upcase = 0;
	for (i=0;i<sPW.length;i++){ 
		//测试每一个字符的类别并统计一共有多少种模式. 
		Modes=CharMode(sPW.charCodeAt(i));
		switch(Modes) 
		{ 
		case 1:
			//数字
			num++;
			break;
		case 2: 
			//大写
			upcase++;
			break; 
		case 4: 
			//小写
			liter++;
			break; 
		case 8:
			//特殊字符
			spical++;
			break;
		}
		
	}
	var result = 0;
	if((num>0&&liter===0&&spical===0&& upcase ===0)||(num===0&&liter>0&&spical===0&& upcase ===0)||(num===0&&liter===0&&spical>0&& upcase ===0)||(num===0&&liter===0&&spical===0&& upcase > 0)){
		//低级
		result = 0;
	}else	if((num > 0 && liter >0&&spical===0&& upcase ===0)||(num > 0 && spical > 0&&liter===0&& upcase ===0)||(liter > 0 && spical > 0&& num ===0&& upcase ===0)||(liter === 0 && spical === 0  && num > 0 && upcase > 0)||(liter > 0 && spical === 0 && num ===0&& upcase > 0)||(liter === 0 && spical > 0&& num ===0&& upcase > 0)){
		//中级
		result =  1;
	}else if((num > 0 && liter> 0 &&spical > 0&& upcase ===0)||(num === 0 && liter> 0 &&spical > 0&& upcase > 0)||(num > 0 && liter === 0 &&spical > 0 && upcase > 0)||(num > 0 && liter> 0 &&spical === 0 && upcase > 0)||(num > 0 && liter> 0 &&spical > 0 && upcase > 0)){
		//高级
		result = 2;
	}
	
	return result; 
}

Date.prototype.Format = function(fmt) { // author: meizz
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};

CBank.datefarmat = function(d, f) {
	if (d && d != '') {
		f = f || 'yyyy-MM-dd hh:mm:ss';
		if (typeof d == 'string' || typeof d == 'number') {
			d = new Date(d);
		}
		return d.Format(f);
	}else{
		return "";
	}
};

CBank.msg = function(msg, fn) {
	if (CBank.msgdiv) {
		CBank.msgdiv.show().msg(msg);
	} else {
		var mhtml = '<div class="popup_info_wrap">' + '<div class="popup_info_main">' + '<h4>提示</h4>'
				+ '<p id="_msg_">' + msg + '</p>' + '<div class="btn_bar">'
				+ '<a href="#" class="link_cancel" id="_msg_cancel_">取消</a>' + '<a href="#" id="_msg_ok_">确定</a>'
				+ '</div>' + '</div>' + '</div>';
		CBank.msgdiv = $(mhtml).appendTo(document.body).show();
		CBank.msgdiv.msg = function(msg) {
			CBank.msgdiv.find('#_msg_').html(msg).show();
			return CBank.msgdiv;
		};
		CBank.msgdiv.find('#_msg_cancel_').on('tap', function() {
			CBank.msgdiv.hide();
			if (typeof fn == 'function') {
				fn(false);
			}
		});
		CBank.msgdiv.find('#_msg_ok_').on('tap', function() {
			CBank.msgdiv.hide();
			if (typeof fn == 'function') {
				fn(true);
			}
		});
	}
};

CBank._per = 0;

CBank.loading = function(doshow,mper){
//	console.info("doshow:"+doshow+",mper:"+(mper?mper:""));
	if(mper){
		CBank._per += mper;
		if(CBank._per>=100){
			CBank._per = 0;
			CBank.loading(false);
			return;
		}
	}
	
	if(CBank.__loading){
		CBank.__loading.remove();
		CBank.scrollDisable = false;
		CBank.__loading=null;
	}
	
	if(doshow && !CBank.__loading){
		CBank.__loading = $('<div class="shadow_bg shadow_bg_w" style=" display:block;"><span class="icon popup_loading" style="font-size: 10px;color:red;">'+(mper&&CBank._per>0?CBank._per+'%':'')+'</span></div>').css({width:$(document.body).width() + 'px',height:$(document.body).height() + 'px'}).appendTo(document.body);
		CBank.scrollDisable = true;
	}
};

CBank.pageTo = function(murl){
	window.location.href = murl;
};

CBank.toast = function(msg, t, url) {
	t = t || 3000;
	var mtoast = $('<div><div>').css({
		'position' : 'absolute',
		'top' : '0px',
		'left' : '0px',
		'width' : $(window).width() + 'px',
		'height' : $(window).height() + 'px'
	}).appendTo(document.body).show();
	var mmsg = $(
			'<div style="position:absolute;color:#fff;background:#343434;font-size:15px;padding:12px;border-radius:10px;">'
			+ msg + '</div>').appendTo(document.body);
	mmsg.css({
		'position' : 'absolute',
		'top' : (window.pageYOffset + ($(window).height() - mmsg.height()) / 2) + 'px',
		'left' : ($(window).width() - mmsg.width()) / 2 + 'px'
	});
	window.setTimeout(function() {
		mtoast.remove();
		mmsg.remove();
		if (url) {
			window.location.href = url;
		}
	}, t);
};
//只弹出一次框
var toast_fun = null;
var toast_div = null;
var toast_msg = null;
CBank.toast_singleton = function(msg, t, url) {
	if(toast_div || toast_msg){
	    clearTimeout(toast_fun);
	    toast_div.remove();
		toast_msg.remove();
	}
	t = t || 3000;
	toast_div = $('<div><div>').css({
		'position' : 'absolute',
		'top' : '0px',
		'left' : '0px',
		'width' : $(window).width() + 'px',
		'height' : $(window).height() + 'px'
	}).appendTo(document.body).show();
	toast_msg = $(
			'<div style="position:absolute;color:#fff;background:#343434;font-size:15px;padding:12px;border-radius:10px;">'
					+ msg + '</div>').appendTo(document.body);
	toast_msg.css({
		'position' : 'absolute',
		'top' : (window.pageYOffset + ($(window).height() - toast_msg.height()) / 2) + 'px',
		'left' : ($(window).width() - toast_msg.width()) / 2 + 'px'
	});
	toast_fun = window.setTimeout(function() {
		toast_div.remove();
		toast_msg.remove();
		toast_div = null;
		toast_msg = null;
		if (url) {
			window.location.href = url;
		}
	}, t);
};

CBank.getAjaxLoading = function() {
	CBank.ajaxLoading = CBank.ajaxLoading
			|| ($(
					'<div class="popup_cover_bg"><div class="popup_loading_main"><img src="../images/loading2.GIF" /></div></div>')
					.hide().appendTo(document.body)).hide();
	return CBank.ajaxLoading;
};

CBank.GPSPostion = function(fn, citycodeFn) {
	if (typeof fn != 'function') {
		return false;
	}

	var locationSuccess = function(position) {
		var coords = position.coords;
		fn({
			lng : coords.longitude,
			lat : coords.latitude
		});
		var url = 'http://api.map.baidu.cogeocoder/v2/?ak=093960115151785132d91041c3a8889a&callback=?&location='
				+ coords.latitude + ',' + coords.longitude + '&output=json&pois=0&coordtype=wgs84ll';
		if (typeof citycodeFn == 'function') {
			$.getJSON(url, function(data) {
				if (data) {
					citycodeFn(data);
					// if(data.result&&data.result.formatted_address){
					// CBank.toast(data.result.formatted_address,2000);
					// }
				}
			});
		}
	};

	var locationError = function(error) {
		switch (error.code) {
		case error.TIMEOUT:
			CBank.toast("获取GPS超时.", 2000);
			break;
		case error.POSITION_UNAVAILABLE:
			CBank.toast('很抱歉无法准确定位,请检测GPS服务是否开启.', 2000);
			break;
		case error.PERMISSION_DENIED:
			CBank.toast('请开启GPS定位服务', 2000);
			break;
		case error.UNKNOWN_ERROR:
			CBank.toast('GPS定位异常，请检测设置.', 2000);
			break;
		}
		CBank.setSession('per_app_city_name', "合肥市");
		CBank.setSession('per_app_city_code', "3610");
	};

	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(locationSuccess, locationError, {
			// 指示浏览器获取高精度的位置，默认为false
			enableHighAcuracy : true,
			// 指定获取地理位置的超时时间，默认不限时，单位为毫秒
			timeout : 60000,
			// 最长有效期，在重复获取地理位置时，此参数指定多久再次获取位置。
			maximumAge : 300000
		});
	} else {
		CBank.toast("您的设备暂不支持GPS定位服务.", 2000);
	}

};
//
CBank.initCommonEventUI= function(hasBottom,hasLeft,hasShopCount){
	if(hasLeft){
		$(".manuelist").on("click","li",function(){
			var atype = $(this).attr("atype");
			if(!atype){
				return true;
			}
			switch(atype){
				case "sy":
					CBank.pageTo(CBank.config.webApp+"index.htm");
					break;
				case "hd":
					CBank.gotoUrl("menu/others_huodong",CBank.config.webApp+"menu/others_huodong.htm");
					break;
				case "jjsx":
					CBank.gotoUrl("menu/activitylist",CBank.config.webApp+"menu/activitylist.htm");
					break;
				case "gy":
					CBank.gotoUrl("other/others_aboutus",CBank.config.webApp+"other/others_aboutus.htm");
					break;
				case "wd":
					CBank.gotoUrl("personal/mymeilihui",CBank.config.webApp+"personal/mymeilihui.htm");
					break;
				case "lq":
					CBank.gotoUrl("personal/mymeilihui_tuijian",CBank.config.webApp+"personal/mymeilihui_tuijian.htm");
					break;
				case "weibo":
					CBank.pageTo("http://m.weibo.cn/u/1722407475?sudaref=www.mei.com");
					break;
				case "help":
					CBank.gotoUrl("other/others_helplist",CBank.config.webApp+"other/others_helplist.htm");
					break;
				case "wl":
					CBank.gotoUrl("menu/mymeilihui_dingdan_list",CBank.config.webApp+"order/mymeilihui_dingdan_list.htm");
					break;
				case "kf":
					CBank.gotoUrl("other/others_silo_wechat",CBank.config.webApp+"other/others_silo_wechat.htm");
					break;
			}
			return false;
		});
	}
	if(hasBottom){
		if(CBank.getSession("mlh_mei_credential")){
			$("#un_login_bottom").hide();
			$("#login_bottom").show();
		}else{
			$("#un_login_bottom").show();
			$("#login_bottom").hide();
		}
		$(".bottomitems").on("click","a",function(){
			var atype = $(this).attr("atype");
			if(!atype){
				return true;
			}
			switch(atype){
				case "sy":
					CBank.pageTo(CBank.config.webApp+"index.html");
					break;
				case "fl":
					CBank.gotoUrl("menu/others_huodong",CBank.config.webApp+"menu/others_huodong.htm");
					break;
				case "jjsx":
					CBank.gotoUrl("menu/activitylist",CBank.config.webApp+"menu/activitylist.htm");
					break;
				case "gy":
					CBank.gotoUrl("other/others_aboutus",CBank.config.webApp+"other/others_aboutus.htm");
					break;
				case "dl":
					CBank.gotoUrl("menu/login",CBank.config.webApp+"menu/login.htm");
					break;
				case "zc":
					CBank.gotoUrl("user/register",CBank.config.webApp+"user/register.htm");
					break;
				case "tc":
					CBank.loginOut(window.location.href);
					break;
				case "wl":
					CBank.gotoUrl("menu/mymeilihui_dingdan_list",CBank.config.webApp+"order/mymeilihui_dingdan_list.htm");
					break;
				case "kf":
					CBank.gotoUrl("other/others_silo_wechat",CBank.config.webApp+"other/others_silo_wechat.htm");
					break;
			}
			return false;
		});
	}
	if(hasShopCount){
		CBank.cartViewCount(function(cartViewCount){
			$("#cartViewCount").html(cartViewCount/1>0?cartViewCount:"");
		});
		$("#cartViewCount").on("click",function () {
		    	CBank.gotoUrl("personal/shopingcart",CBank.config.webApp+"personal/shopingcart.htm");
		    	return false;
		});
	}
}
CBank.showqrcode = function(model, callback) {
	model = model || 'personal';
	if (typeof callback == 'function') {
		CBank.qrcodecallback = callback;
	}
	if (window.CBankAndroid) {
		window.CBankAndroid.ReadQRCode();
	} else {
		var murl = window.location.href + '';
		var mcommand = '#' + model + '_CBank_COMMAND_' + 'showqrcode';
		if (murl && murl.indexOf('#') != -1) {
			murl = murl.split('#')[0];
		}
		window.location.href = murl + '#clean';
		window.location.href = murl + mcommand;
	}
};

CBank.qrcodecallback = function(mcode) {
	alert(mcode);
};

CBank.showAjaxLoading = false;
CBank.isMock = false;

document.CBank = window.CBank;

CBank.setSession("checkCookieIsOk", "1");
if (CBank.getSession("checkCookieIsOk") != "1") {
	CBank.toast("请打开Cookie");
};


CBank.pmobile = function(val) {
	var p = /^(13[0-9]|15[0-9]|18[0-9])\d{8}$/;
	if (p.test(val)) {
		return true;
	}
	return false;
};

CBank.fn.init.prototype = CBank.fn;

window.CBank = CBank;
//默认加载失败的图片地址
CBank.onError = function(obj) {
	var default_img = "product_img_default.png";
//	var default_img = "banner3.jpg";
//	var default_img = "default_medium.jpg";
	if ($(obj).attr("default_img")) {
		default_img = $(obj).attr("default_img");
	}
	$(obj).attr("src",CBank.config.defaultImgAddr+default_img);
	return false;
};

//新首页地址
CBank.onError2 = function(obj) {
	var default_img = "product_img_default.png";
//	var default_img = "banner3.jpg";
//	var default_img = "default_medium.jpg";
	if ($(obj).attr("default_img")) {
		default_img = $(obj).attr("default_img");
	}
	$(obj).attr("src",CBank.config.defaultImgAddr2+default_img);
	return false;
};
//soli页
CBank.onError3 = function(obj) {
	var default_img = "product_img_default.png";
//	var default_img = "banner3.jpg";
//	var default_img = "default_medium.jpg";
	if ($(obj).attr("default_img")) {
		default_img = $(obj).attr("default_img");
	}
	$(obj).attr("src",CBank.config.defaultImgAddr3+default_img);
	return false;
};
/*==========横向可拖动导航=========*/
window.Swipe = function (b, a) {
    if (!b) {
        return null;
    }
    var c = this;
    this.options = a || {};
    this.index = this.options.startSlide || 0;
    this.speed = this.options.speed || 300;
    this.lwidth = this.options.width || 80; //导航li宽度
    this.delay = this.options.auto || 0; //自动滚动菜单速度0为不自动滚动
    this.col = this.options.auto || 4; //每排显示个数
    this.container = b;
    this.element = this.container.children[0];
    this.container.style.overflow = "hidden";
    this.element.style.listStyle = "none";
    this.element.style.margin = 0;
    this.setup();
    if (this.delay != 0) {
        this.begin();
    }
    if (this.element.addEventListener) {
        this.element.addEventListener("touchstart", this, false);
        this.element.addEventListener("touchmove", this, false);
        this.element.addEventListener("touchend", this, false);
        this.element.addEventListener("touchcancel", this, false);
        this.element.addEventListener("webkitTransitionEnd", this, false);
        this.element.addEventListener("msTransitionEnd", this, false);
        this.element.addEventListener("oTransitionEnd", this, false);
        this.element.addEventListener("transitionend", this, false);
        window.addEventListener("resize", this, false);
    }
};

Swipe.prototype = {
    setup: function () {
        this.slides = this.element.children;

        this.width = Math.ceil(("getBoundingClientRect" in this.container) ? this.container.getBoundingClientRect().width : this.container.offsetWidth);
        if (!this.width) {
            return null;
        }
        this.length = this.slides.length;
        this.length = Math.ceil(this.slides.length / 4);
        if (this.length < 1) {
            return null;
        }

        this.container.style.visibility = "hidden";
        //this.element.style.width = Math.ceil(this.slides.length * this.lwidth) + "px";
        var a = this.slides.length;
        while (a--) {
            var b = this.slides[a];
            //b.style.width = this.lwidth + "px";
            // b.style.display = "table-cell";
            // b.style.verticalAlign = "top"
        }
        this.slide(this.index, 0);
        this.container.style.visibility = "visible"
    },
    slide: function (a, c) {
        var b = this.element.style;
        if (c == undefined) {
            c = this.speed;
        }
        b.webkitTransitionDuration = b.MozTransitionDuration = b.msTransitionDuration = b.OTransitionDuration = b.transitionDuration = c + "ms";
        b.MozTransform = b.webkitTransform = "translate3d(" + -(a * this.width) + "px,0,0)";
        b.msTransform = b.OTransform = "translateX(" + -(a * this.width) + "px)";
        this.index = a;
    },
    getPos: function () {
        return this.index;
    },
    prev: function (a) {
        this.delay = a || 0;
        clearTimeout(this.interval);
        if (this.index) {
            this.slide(this.index - 1, this.speed);
        } else {
            this.slide(this.length - 1, this.speed);
        }
    },
    next: function (a) {
        this.delay = a || 0;
        clearTimeout(this.interval);
        if (this.index < this.length - 1) {
            this.slide(this.index + 1, this.speed);
        } else {
            this.slide(0, this.speed);
        }
    },
    begin: function () {
        var a = this;
        this.interval = (this.delay) ? setTimeout(function () {
            a.next(a.delay);
        },
        this.delay) : 0;
    },
    stop: function () {
        this.delay = 0;
        clearTimeout(this.interval);
    },
    resume: function () {
        this.delay = this.options.auto || 0;
        this.begin();
    },
    handleEvent: function (a) {
        switch (a.type) {
            case "touchstart":
                this.onTouchStart(a);
                break;
            case "touchmove":
                this.onTouchMove(a);
                break;
            case "touchcancel":
            case "touchend":
                this.onTouchEnd(a);
                break;
            case "webkitTransitionEnd":
            case "msTransitionEnd":
            case "oTransitionEnd":
            case "transitionend":
                this.transitionEnd(a);
                break;
            case "resize":
                this.setup();
                break;
        }
    },
    transitionEnd: function (a) {
        if (this.delay) {
            this.begin();
        }

    },
    onTouchStart: function (a) {
        this.start = {
            pageX: a.touches[0].pageX,
            pageY: a.touches[0].pageY,
            time: Number(new Date())
        };
        this.isScrolling = undefined;
        this.deltaX = 0;
        this.element.style.MozTransitionDuration = this.element.style.webkitTransitionDuration = 0;
        a.stopPropagation();
    },
    onTouchMove: function (a) {
        if (a.touches.length > 1 || a.scale && a.scale !== 1) {
            return
        }
        this.deltaX = a.touches[0].pageX - this.start.pageX;
        if (typeof this.isScrolling == "undefined") {
            this.isScrolling = !!(this.isScrolling || Math.abs(this.deltaX) < Math.abs(a.touches[0].pageY - this.start.pageY));
        }
        if (!this.isScrolling) {
            a.preventDefault();
            clearTimeout(this.interval);
            this.deltaX = this.deltaX / ((!this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0) ? (Math.abs(this.deltaX) / this.width + 1) : 1);
            this.element.style.MozTransform = this.element.style.webkitTransform = "translate3d(" + (this.deltaX - this.index * this.width) + "px,0,0)";
            a.stopPropagation();
        }
    },
    onTouchEnd: function (c) {
        var b = Number(new Date()) - this.start.time < 250 && Math.abs(this.deltaX) > 20 || Math.abs(this.deltaX) > this.width / 2,
        a = !this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0;
        if (!this.isScrolling) {
            this.slide(this.index + (b && !a ? (this.deltaX < 0 ? 1 : -1) : 0), this.speed);
        }
        c.stopPropagation();
    }
};
//获取客户端的高度
CBank.getClientWidth = function(){
	return $(window).width();
}
//图片配置
CBank.imageConfig = function(path1,path2){
	_config = {
			"event/product":{
				"product":{
					width:300,
					height:400,
					weight:90,
				},
				"brandlogo":{
					width:232,
					height:238,
					weight:90,
				},
				"share":{
					width:640,
					height:326,
					weight:90,
				},
				"gift":{
					width:240,
					height:320,
					weight:90,
				}
			},
			"product/detail":{
				"large":{
					width:720,
					height:960,
					weight:90,
				},
				"small":{
					width:225,
					height:300,
					weight:90,
				},
				"share":{
					width:300,
					height:326,
					weight:90,
				},
				"gift":{
					width:240,
					height:320,
					weight:90,
				}
			},
			"product/detail":{
				"large":{
					width:720,
					height:960,
					weight:90,
				},
				"small":{
					width:225,
					height:300,
					weight:90,
				},
				"share":{
					width:300,
					height:326,
					weight:90,
				},
				"gift":{
					width:240,
					height:320,
					weight:90,
				}
			},
			"home/event":{
				"event":{
					width:640,
					height:326,
					weight:90,
				}
			},
			"home/marketingBanner":{
				"banner":{
					width:640,
					height:326,
					weight:90,
				}
			},
			"upcoming/index":{
				"event":{
					width:143,
					height:85,
					weight:90,
				}
			}
	}
	return _config[path1][path2];
}
//微博分享
function weiboShare(sharetitle,weiboPath,cloudPath){
	//微博分享显示连接
	//微博分享显示连接——短链接
	$.ajax({
		type: "GET",
//		url: "http://api.t.sina.com.cn/short_url/shorten.json",
		url: "https://api.weibo.com/2/short_url/shorten.json",
		dataType: 'jsonp',
		jsonp:'callback',
		async:false,
		data: {
			source:"1903943638",
			url_long:weiboPath
		},
		success: function(data){
			url_short = data.data.urls[0].url_short;
			//window.sharetitle = "Hey，我发现一家超赞的时尚网站—魅力惠，风格、价格都魅力十足！看到的小伙伴们快来点击我的链接领取80元专属优惠券";
			//window.shareUrl = url_short;
			share(sharetitle, url_short,cloudPath);
		}
	});
}
function share(sharetitle,url_short,cloudPath){
	//d指的是window
	(function(s,d,e){
		try{
			
		}catch(e){
			
		}
		var f='http://v.t.sina.com.cn/share/share.php?',
		u=d.location,
		p=['url='+url_short,'&title=',e(sharetitle),'&appkey='+CBank.config.appkey,'&pic=',e(cloudPath)].join('');
		function a(){
				if(!window.open([f,p].join(''),
				'mb',
				['toolbar=0,status=0,resizable=1,width=620,height=450,left=',(s.width-620)/2,',top=',(s.height-450)/2].join('')))
				u.href=[f,p].join('');
		};
		if(/Firefox/.test(navigator.userAgent)){
			  setTimeout(a,0);
	    }else{
	    	a();
	    }
	}
	)(screen,document,encodeURIComponent);
}
//有openId直接跳登陆
var openId = CBank.getParam("openid");
if(openId){
 	CBank.setSession("openId", openId);
 	CBank.winLoginOut(openId);
}
if (!CBank.getSession("mlh_mei_credential")) {
	var needlogin = true;
	var tref = window.location.href + '';
	if(tref&&(tref.indexOf("other/") != -1||tref.indexOf("menu/") != -1||tref.indexOf("index") != -1||tref.indexOf("silo") != -1||tref.indexOf("user") != -1)){
		needlogin = false;
	}else{
		for ( var i = 0; i < mhref.length; i++) {
			var thehref = mhref[i];
			if (tref.indexOf(thehref) != -1) {
				needlogin = false;
				break;
			}
		}
	}
	if (needlogin) {
		CBank.gotoUrl("menu/login",CBank.config.webApp+CBank.config.loginAddr,tref,CBank.config.webApp+"index.html");
	}
}